import { SVNClient } from '@taiyosen/easy-svn';
import fs from 'fs-extra';
import path from 'path';
import { BuildParams } from '../BuildParams.js';
import { LogParser } from '../LogParser.js';
import { Cmd } from './Cmd.js';

export class JsonBuilder {
    async build_bjson(exePath: string, buildParams: BuildParams, svnClient: SVNClient, logParser: LogParser) {
        console.time('Build bjson');

        const folders = [''];
        if (buildParams.channelCfg['localize-params']) {
            const arr = buildParams.channelCfg['localize-params'].split(/\s+/);
            for (let i = 0, len = arr.length; i < len; i++) {
                if (arr[i] == '--langs') {
                    const langs = arr[i + 1].split(',');
                    folders.push(...langs);
                }
            }
        }

        for (let folder of folders) {
            const dstpath = path.join(buildParams.workSpacePath, `Assets/AssetSources/bjsondata${folder}`);
            if(fs.existsSync(dstpath)) {
                const lastfiles = fs.readdirSync(dstpath);
                for(let f of lastfiles) {
                    if(path.extname(f) == '.bytes') {
                        fs.removeSync(path.join(dstpath, f));
                    }
                }
            } else {
                fs.mkdirSync(dstpath);
            }
    
            const srcpath = path.join(buildParams.workSpacePath, `Assets/AssetSources/data${folder}`);
            const files = fs.readdirSync(srcpath);
            for(let f of files) {
                if (path.extname(f) != '.json') continue;
                let d = path.join(dstpath, f.replace('.json', '.bytes'));
                const cmd = new Cmd();
                const errcode = await cmd.run(exePath, [path.join(srcpath, f), d], { silent: true });
                logParser.parseUnityBuildLog(cmd.output, errcode);
                if(logParser.error) {
                    process.exit(1);
                }
            }
            
            // await svnClient.addUnversioned(dstpath);
            // await svnClient.commit(dstpath, 'auto commit by builder');
        }        

        console.time('Build bjson');
    }
}